<template>
  <div>
    <div id="map" ref="mapContainer" class="map"></div>
  </div>
</template>

<script>
import {onMounted, ref} from 'vue';
import "ol/ol.css";
import Map from 'ol/Map';
import View from 'ol/View';
import {layersData,mapconfig} from './mapLayers'
import {BaseLayerSwitcherToolBar} from './loadSwitcherMap'

export default {
  name: "baseMap",
  setup() {
    const mapContainer = ref(null); // 使用 ref 创建响应式引用
    const mapInstance = ref(null);  // 存储地图实例的引用
    // 初始化地图的方法
    const initMap = () => {

      // 创建地图实例
      mapInstance.value = new Map({
        target: mapContainer.value, // 使用 ref 引用的 DOM 元素作为目标
        layers: layersData,
        view: new View({
          center: [0, 0], // 根据需要设置中心
          zoom: 2,        // 根据需要设置缩放级别
        }),
      });
    };
    const addControls = () => {
      loadSwitcherMap(mapconfig); // 底图切换控件加载
    };

    const loadSwitcherMap = (data) => {
      const baseLayerSwitcherToolbar = new BaseLayerSwitcherToolBar({
        data
      });
      document.getElementById("map").appendChild(baseLayerSwitcherToolbar.target);
      baseLayerSwitcherToolbar.onItemClick = function (itemData) {
        let data = itemData;
        layersData.forEach(function (layer) {
          data.layer_id === layer.get('key') ? layer.setVisible(true) : layer.setVisible(false);
        });
        console.log(layersData);
      };
    };

    // 组件挂载后初始化地图
    onMounted(() => {
      initMap();
      addControls();
    });

    // 返回在模板中需要的变量
    return {
      mapContainer,
      mapInstance
    };
  }
};
</script>
<style>
.map {
  width: 100%;
  height: 100vh;
}
/*底图切换控件*/
.map_switch {
  position: absolute;
  right: 50px;
  top: 15px;
  font-family: "宋体";
  font-size: 12px;
  width: 70px;
  z-index: 999;
}

.map_switch_item {
  width: 58px;
  height: 60px;
  border: 1px solid #b1b1b1;
  text-align: center;
  float: right;
  display: inline;
  margin-left: 10px;
  background-color: #fff;
  cursor: pointer;
}

.hoverType:hover {
  width: 56px;
  height: 58px;
  background-color: #c6e0f7;
  margin: auto;
}

.hoverType {
  width: 56px;
  height: 58px;
  background-color: #fff;
  margin: auto;
}

.vecType {
  width: 56px;
  height: 38px;
  background: url(../assets/indexImage.png) no-repeat -154px -202px;
}

.imgType {
  width: 56px;
  height: 38px;
  background: url(../assets/indexImage.png) no-repeat -154px -155px;
}

.terType {
  width: 56px;
  height: 38px;
  background: url(../assets/indexImage.png) no-repeat -86px -202px;
}

.map_bom {
  height: 22px;
  line-height: 22px;
  color: #333333;
}
</style>
